/******************************************************************************
 * Copyright (C) 2024 EternalChip, Inc.(Gmbh) or its affiliates.
 *
 * All Rights Reserved.
 *
 * @file bsp_key.c
 *
 * @par dependencies
 * - bsp_key.h
 * - stdio.h
 * - stdint.h
 *
 * @author Cuihan
 *
 * @brief Provide the HAL APIs of AHT21 and corresponding opetions.
 *
 * Processing flow:
 *
 * call directly.
 *
 * @version V1.0 2024-12-24
 *
 * @note 1 tab == 4 spaces!
 *
 *****************************************************************************/

//******************************** Includes *********************************//

#include "bsp_key.h"
#include "main.h"

//******************************** Global Variables *********************************//
const osThreadAttr_t key_Task_attributes = {
    .name = "key_Task",
    .stack_size = 128 * 4,
    .priority = (osPriority_t)osPriorityNormal + 1,
};

osThreadId_t key_TaskHandle;
QueueHandle_t key_QueueHandle;

key_status_t key_scan(key_press_status_t *key_value)
{
    uint32_t counter = 0;
    key_press_status_t key_status_value = KEY_NOT_PRESSED;
    
    // 按键按下
    if (HAL_GPIO_ReadPin(KEY_GPIO_Port, KEY_Pin) == GPIO_PIN_RESET)
    {
        // 按键按下,延时消抖
        osDelay(10);
        if (HAL_GPIO_ReadPin(KEY_GPIO_Port, KEY_Pin) == GPIO_PIN_RESET)
        {
            key_status_value = KEY_PRESSED;
        }
        *key_value = key_status_value;
        return KEY_OK;
    }
}

void key_task_func(void *argument)
{
    key_press_status_t key_status = KEY_NOT_PRESSED;
    key_status_t key_ret = KEY_OK;

    // 创建键值队列 
    key_QueueHandle = xQueueCreate(10, sizeof(key_press_status_t));
    if (key_QueueHandle == 0)
    {
        printf("Queue was not created and must not be used. \n");
        // Queue was not created and must not be used.
    }
    else
    {
        printf("Queue was created successfully. \n");
    }

    for (;;)
    {
        // 按键检测
        key_ret = key_scan(&key_status);

        if (KEY_OK == key_ret)
        {
            if (KEY_PRESSED == key_status)
            {
                printf("key is pressed \n");
                if (pdPASS == xQueueSend(key_QueueHandle, &key_status, 0))
                {
                    printf("key value send successful\n");
                }
            }
        }
        osDelay(10);
    }
}
